﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Rally_like_a_madman.Data;

namespace Rally_like_a_madman
{
    public partial class HighscoresPage : PhoneApplicationPage
    {
        public HighscoresPage()
        {
            InitializeComponent();

            retrieveRoutesFromDatabase();
        }

        /// <summary>
        /// 
        /// </summary>
        private void retrieveRoutesFromDatabase()
        {
            App thisApp = Application.Current as App;
            var tmpRoutes = from Route route in thisApp.ActiveDB.RouteTable select route;

            List<Route> existingRoutes = tmpRoutes.ToList() as List<Route>;

            lbRoutes.ItemsSource = existingRoutes;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void lbRoutes_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            App thisApp = Application.Current as App;
            var tmpScores = (from Score score in thisApp.ActiveDB.ScoreTable
                             where (score.Route.IDRoute == (lbRoutes.SelectedItem as Route).IDRoute) 
                             orderby score.Time ascending select score).Take(5);

            List<Score> existingScores = tmpScores.ToList() as List<Score>;

            fillHighscores(existingScores);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="existingScores"></param>
        private void fillHighscores(List<Score> existingScores)
        {
            int count = existingScores.Count;

            tbHighscore1.Text = tbHighscore2.Text = tbHighscore3.Text = tbHighscore4.Text = tbHighscore5.Text = " ";

            if (count > 0)
                tbHighscore1.Text = "#1 " + existingScores[0].ToString();

            if (count > 1)
                tbHighscore2.Text = "#2 " + existingScores[1].ToString();

            if (count > 2)
                tbHighscore3.Text = "#3 " + existingScores[2].ToString();

            if (count > 3)
                tbHighscore4.Text = "#4 " + existingScores[3].ToString();

            if (count > 4)
                tbHighscore5.Text = "#5 " + existingScores[4].ToString();
        }
    }
}